import pymysql


# username : adil
# password : helloyyj

class DataBaseHandle(object):
    def __init__(self, host, username, password, database, port):
        '''初始化数据库信息并创建数据库连接'''
        # 下面的赋值其实可以省略，connect 时 直接使用形参即可
        self.host = host
        self.username = username
        self.password = password
        self.database = database
        self.port = port
        self.db = pymysql.connect(
            host=self.host,
            user=self.username,
            password=self.password,
            database=self.database,
            port=self.port,
            charset="utf8"

        )
        self.cursor = self.db.cursor(pymysql.cursors.DictCursor)

    def select_info(self, sql):
        try:
            self.cursor.execute(sql)
            data = self.cursor.fetchall()
            print(data)
            return data
        except Exception as e:
            raise e
        finally:
            self.cursor.close()

    def no_select_info(self, sql):
        try:
            result = self.cursor.execute(sql)
            print(result)
            self.db.commit()
            return result
        except Exception as e:
            self.db.rollback()
            raise e
        finally:
            self.cursor.close()


if __name__ == '__main__':
    Data = DataBaseHandle('localhost', 'root', '123', 'mxn0526', 3306)